package code.c11;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/11/17 10:15
 * @package code.c11
 * @description 自定义 JFrame
 */

public class MyFrame1 extends JFrame {
    public MyFrame1(String title) throws HeadlessException {
        super.setTitle(title);
        this.init();
    }

    public void init() {
        super.setSize(485, 300);
        super.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        super.setLayout(new FlowLayout());


        JButton button_1 = new JButton("button_1");
        JTextField jTextField = new JTextField(10);

        // 定义一个事件监听器
        button_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // 读取文本框中的数字
                    int num = Integer.parseInt(jTextField.getText());
                    System.out.println(num);
                    // 将数字平方后输入到文本框中
                    jTextField.setText(String.valueOf(Math.pow(num,2)));
                    System.out.println(num * num);
                } catch (NumberFormatException numberFormatException) {
                    numberFormatException.printStackTrace();
                } finally {
                    jTextField.setText("数据转换失败，请重新输入正确的数字");
                }
            }
        });

        super.add(button_1);
        super.add(jTextField);
        super.setVisible(true);
    }
}
